#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
运行所有测试的主脚本
"""

import sys
import os
import importlib

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def run_test_module(module_name, function_name="run_all_tests"):
    """运行单个测试模块"""
    try:
        module = importlib.import_module(f".{module_name}", package="tests")
        if hasattr(module, function_name):
            func = getattr(module, function_name)
            return func()
        else:
            print(f"[警告] 模块 {module_name} 没有找到函数 {function_name}")
            return False
    except Exception as e:
        print(f"[错误] 运行模块 {module_name} 时出错: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """主函数"""
    print("开始运行所有测试...")
    print("=" * 60)

    # 定义要运行的测试模块
    test_modules = [
        ("test_core_modules", "test_all"),
        ("test_smart_matching", "run_all_tests"),
        ("test_cache_strategy", "run_all_tests"),
        ("test_cache_optimization", "run_all_tests"),
        ("test_integration", "run_all_tests"),
    ]

    results = []

    for module_name, function_name in test_modules:
        print(f"\n🔄 正在运行 {module_name}...")
        result = run_test_module(module_name, function_name)
        results.append((module_name, result))

        if result:
            print(f"✅ {module_name} 测试通过")
        else:
            print(f"❌ {module_name} 测试失败")

    # 汇总结果
    print("\n" + "=" * 60)
    print("测试结果汇总:")

    passed_count = sum(1 for _, result in results if result)
    total_count = len(results)

    for module_name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"  {module_name}: {status}")

    print("\n总计: {}/{} 个测试模块通过".format(passed_count, total_count))

    if passed_count == total_count:
        print("\n🎉 恭喜！所有测试都通过了！")
        print("重构后的教室查询系统功能正常，可以投入使用。")
        return True
    else:
        print("\n⚠️  部分测试失败，请检查相关功能。")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)